package org.jprogger.myworld.api.response.handler;

import org.jprogger.myworld.api.ApiServiceInvocationException;
import org.jprogger.myworld.api.app.ApiParams;
import org.jprogger.myworld.api.request.ApiRequest;
import org.jprogger.myworld.api.response.ApiResponse;
import org.jprogger.myworld.api.response.AbstractApiResponseHandler;
import org.jprogger.myworld.api.response.ApiResponseData;
import org.jprogger.myworld.api.response.ApiResponseError;
import org.jprogger.myworld.api.response.DefaultApiResponse;
import org.jprogger.myworld.api.response.DefaultApiResponseData;
import org.jprogger.myworld.api.response.ParseResponseException;
import org.json.JSONException;
import org.json.JSONObject;

public class HasAppPermApiResponseHandler extends AbstractApiResponseHandler<Integer> {

	@Override
	public ApiResponse<Integer> handleResponse(ApiRequest request, String response) throws ApiServiceInvocationException {
		
		ApiResponseError apiError = null;
		ApiResponseData<Integer> apiData = null;
		ApiResponse<Integer> apiResponse = new DefaultApiResponse<Integer>();
		String format = request.getRequestFormat();
		try 
		{
			apiError = validateResponse(response, format);
			if (apiError == null)
			{
				if (format.equals(ApiParams.JSON_REQUEST_FORMAT)) 
				{
					apiData = new DefaultApiResponseData<Integer>();
					JSONObject jsonResponse = new JSONObject(response);
					if (jsonResponse.has("stream"))
					{
						Integer audioResult = jsonResponse.getInt("stream");
						apiData.setData(audioResult);
					}
				}
				else if (format.equals(ApiParams.XML_REQUEST_FORMAT))
				{
					// TODO: implement XML response format 
					throw new ApiServiceInvocationException("Unsupported response format");
				}
			}
			apiResponse.setError(apiError);
			apiResponse.setResponseData(apiData);
		} 
		catch (JSONException e)
		{
			throw new ApiServiceInvocationException("Bad response format", e);
		}
		catch (ParseResponseException e) 
		{
			throw new ApiServiceInvocationException("Unable to parse response", e);
		}
		return apiResponse;
	}
}
